package per.wsj.workmanager

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.work.*
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.content_main.*
import per.wsj.commonlib.utils.LogUtil
import android.os.PersistableBundle
import android.content.ComponentName
import android.app.job.JobInfo
import android.app.job.JobScheduler
import android.content.Context


class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        setSupportActionBar(toolbar)

        fab.setOnClickListener { view ->
            startJob()
        }
        tvStatus.setOnClickListener {
            LogUtil.LOGD("---cancel---")
            jobScheduler.cancel(100)
        }
    }

    private val jobScheduler: JobScheduler
        get() {
            val schedulerService = getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler
            return schedulerService
        }

    private fun startJob(){

        val builder = JobInfo.Builder(100, ComponentName(packageName,MyJobService::class.java.name))

        // 5.0,6.0可以设置任意时间间隔，7.0后至少15分钟
        builder.setPeriodic(5*1000)

        //设置至少延迟多久后执行，与周期性违背，不能同时设置
//        builder.setMinimumLatency(5 * 1000)

        //设置最多延迟多久后执行，单位毫秒。
//        builder.setOverrideDeadline(15 * 1000)

        //设置需要的网络条件，有三个取值：
        //JobInfo.NETWORK_TYPE_NONE（无网络时执行，默认）、
        //JobInfo.NETWORK_TYPE_ANY（有网络时执行）、
        //JobInfo.NETWORK_TYPE_UNMETERED（网络无需付费时执行）
        builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)

        // 是否在空闲时执行
        builder.setRequiresDeviceIdle(false)

        // 是否在充电时执行
        builder.setRequiresCharging(true)

        // 重启后是否继续执行
        builder.setPersisted(true)

        // Extras, work duration.
        val extras = PersistableBundle()
        extras.putLong("WORK_DURATION_KEY", 10 * 1000)
        builder.setExtras(extras)

        val schedulerService = jobScheduler
        schedulerService.schedule(builder.build())


    }

    private fun startWork() {
        val request = OneTimeWorkRequestBuilder<MainWorker>()
            .setConstraints(
                Constraints.Builder()
                    .setRequiredNetworkType(NetworkType.CONNECTED)
                    .build()
            )
            .setInputData(Data.Builder().putInt("times", 10).build())
            .addTag("Wangsj")
            .build()

        WorkManager.getInstance().enqueue(request)

//        LogUtil.LOGE("id:" + request.id)
        tvStatus.text = "id:${request.id}\n"

        val result = WorkManager.getInstance().getWorkInfoByIdLiveData(request.id)
//        WorkManager.getInstance().getWorkInfosByTagLiveData()
        result.observe(this, Observer<WorkInfo> {
            tvStatus.text = tvStatus.text.toString() + "state:" + it.state.toString() + "\n"
            tvStatus.text = tvStatus.text.toString() + "tag:" + it.tags.toString() + "\n"
            tvStatus.text = tvStatus.text.toString() + "output:" + it.outputData.getString("result") + "\n"
            tvStatus.text = tvStatus.text.toString() + "-------------------end-----------------" + "\n"
            LogUtil.LOGE("id:" + it.id)
            LogUtil.LOGE("state:" + it.state.toString())
            LogUtil.LOGE("tag:" + it.tags.toString())
            LogUtil.LOGE("output:" + it.outputData.getString("result"))
            LogUtil.LOGE("-------------------end-----------------")
        })
    }
}
